import React from 'react';
import { connect } from 'react-redux';
import { messages } from 'share/common';
import errorMessage from 'share/errorMessage';
import {Form, Spin, Input, Row, Col, DatePicker, Affix, Button, Divider, Icon, message, Select, InputNumber, TimePicker} from 'antd';
const FormItem = Form.Item;
const TextArea = Input.TextArea;
const Option = Select.Option;
import moment from 'moment';
import travelService from 'containers/request/travel-request/travel.service'
import travelUtil from 'containers/request/travel-request/travelUtil'
import TravelLocation from 'containers/request/travel-request/comp/location'
import TravelPrompt from 'containers/request/travel-request/travel-prompt'

class TravelDining extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      editData: null, //编辑状态下的行程数据
      currentScenes: [],
      selectScene: null,
      cityName: '',
      cityCode: '',
      baseStartDate: null,
      baseEndDate: null,
      startDate: null, //用餐日期的开始日期
      endDate: null, //用餐日期的结束日期
      amount: null,
      remark: '',
      diningConfig: null,
      standardEnable: false, //是否走差旅标准
      promptList: [] //行程提示语的配置
    };
  };

  componentWillMount() {
    this.initConfig();
    this.initScenes();
  };

  componentWillReceiveProps() {
    const { params } = this.props;
    const { editData } = this.state;
    if (params.isResetDining) {
      this.resetValue();
      delete params.isResetDining;
      delete params.editDining;
      return;
    } else {
      let baseStartDate = travelUtil.getFormHeadValue(params.defaultValue, 'start_date');
      this.setState({baseStartDate: moment(baseStartDate)});
      let baseEndDate = travelUtil.getFormHeadValue(params.defaultValue, 'end_date');
      this.setState({baseEndDate: moment(baseEndDate)});
      if (params.editDining) {
        this.setState({editData: params.editDining}, ()=> {
          delete params.editDining;
          this.initEditData();
        });
      }
      if (!params.editDining && !editData) {
        if (baseStartDate) {
          this.setState({startDate: moment(baseStartDate)});
        }
        if (baseEndDate) {
          this.setState({endDate: moment(baseEndDate)});
        }
      }
    }
  };

  initEditData = () => {
    const { editData } = this.state;
    this.setState({
      selectScene: JSON.parse(JSON.stringify(editData.diningSceneDTO)),
      cityName: editData.cityName,
      cityCode: editData.cityCode,
      amount: editData.standardAmount,
      startDate: moment(editData.startDate),
      endDate: moment(editData.endDate),
      remark: editData.remark
    });
  };

  resetValue = () => {
    const { baseStartDate, baseEndDate } = this.state;
    this.setState({
      editData: null, //编辑状态下的行程数据
      selectScene: null,
      cityName: '',
      cityCode: '',
      startDate: baseStartDate, //用餐日期的开始日期
      endDate: baseEndDate, //用餐日期的结束日期
      amount: null,
      remark: ''
    });
  };

  //初始化用餐行程的配置
  initConfig = () => {
    const { customFormPropertyMap } = this.props.params['travelInfo'];
    if (customFormPropertyMap['application.property.control.fields.dining']) {
      this.setState({diningConfig: JSON.parse(customFormPropertyMap['application.property.control.fields.dining'])});
    }
    this.setState({
      standardEnable: customFormPropertyMap['ca.travel.applypolicy.enable'] === 'true',
      promptList: customFormPropertyMap['travel.itinerary.tips'] ? JSON.parse(customFormPropertyMap['travel.itinerary.tips']) : []
    });
  };

  //初始化用餐类型可选范围
  initScenes = () => {
    const { formOID } = this.props.params['travelInfo'];
    travelService.getDiningScene(formOID).then(res => {
      this.setState({currentScenes: res.data || []});
    }).catch(e => {
      errorMessage(e.response);
    });
  };

  //选择规则
  selectScene = (e, opt) => {
    this.setState({selectScene: opt.props['data-scene']});
  };

  selectCity = (cityObj) => {
    this.setState({
      cityName: cityObj.adName || '',
      cityCode: cityObj.adCode || ''
    });
  };

  //关闭侧滑
  closeDiningSlide = () => {
    this.props.close();
  };

  disabledDate = (current) => {
    const { baseStartDate, baseEndDate } = this.state;
    return !(moment(current).isSame(baseStartDate, 'day')
    || moment(current).isSame(baseEndDate, 'day')
    || moment(current).isBetween(baseStartDate, baseEndDate, 'day'));
  };

  handleChangeDate = (value, key) => {
    this.setState({[key]: value});
  };

  //金额修改
  handleChangeAmount = (num, key) => {
    this.setState({[key]: num});
  };

  handleChangeRemark = (e) => {
    this.setState({remark: e.target.value});
  };

  handleSave = () => {
    const { params } = this.props;
    if (this.validateData()) {
      let submitData = this.getProcessValue();
      this.setState({loading: true});
      if (!submitData.itineraryOID) {
        travelService.travelDiningSubmit(params.oid, [submitData]).then(res => {
          this.setState({loading:false});
          message.success(messages('request.key189'/*已保存*/));
          this.closeDiningSlide();
        }).catch(err=>{
          this.setState({loading:false});
          errorMessage(err.response);
        });
      } else {
        travelService.travelDiningUpdate(submitData).then(res => {
          this.setState({loading:false});
          message.success(messages('request.key189'/*已保存*/));
          this.closeDiningSlide();
        }).catch(err=>{
          this.setState({loading:false});
          errorMessage(err.response);
        });
      }
    }
  };

  //是否校验通过
  validateData = () => {
    const { selectScene, cityCode, startDate, endDate, amount, diningConfig, standardEnable, remark } = this.state;
    if (!selectScene) {
      message.error(messages('request.key631')/*请选择用餐类型*/);
      return false;
    }
    if (diningConfig && diningConfig.city.show && diningConfig.city.required && !cityCode) {
      message.error(messages('request.key632')/*请选择用餐城市*/);
      return false;
    }
    if (!startDate) {
      message.error(messages('request.key503')/*请输入开始日期*/);
      return false;
    }
    if (!endDate) {
      message.error(messages('request.key504')/*请输入结束日期*/);
      return false;
    }
    if (moment(startDate).isAfter(endDate, 'day')) {
      message.error(messages('request.key506')/*结束日期不能早于开始日期*/);
      return false;
    }
    if (diningConfig && diningConfig.diningRule.show && !standardEnable && (amount === null || amount === undefined)) {
      message.error(messages('request.key633')/*请输入用餐标准*/);
      return false;
    }
    if (diningConfig && diningConfig.remark && diningConfig.remark.show && diningConfig.remark.required && !remark) {
      message.error(messages('request.key678')/*请输入备注*/);
      return false;
    }
    return true;
  };

  getProcessValue = (values) => {
    const { selectScene, cityName, cityCode, startDate, endDate, amount, remark, editData } = this.state;
    let submitData = {};
    if (editData) {
      submitData = JSON.parse(JSON.stringify(editData));
    }
    submitData.diningSceneId = selectScene.id;
    submitData.cityName = cityName;
    submitData.cityCode = cityCode;
    //日期的时间置为零点
    let startDateStr = moment(startDate).format('YYYY-MM-DD');
    submitData.startDate = moment(startDateStr).utc().format();
    let endDateStr = moment(endDate).format('YYYY-MM-DD');
    submitData.endDate = moment(endDateStr).utc().format();
    submitData.standardAmount = amount;
    submitData.remark = remark;
    return submitData;
  };

  render() {
    const { loading, selectScene, currentScenes, cityName, startDate, endDate, amount, remark, diningConfig, standardEnable, promptList } = this.state;
    return (
      <div className="travel-dining">
        <TravelPrompt promptList={promptList} type={1010} />
        <Row style={{marginBottom: 10, marginTop: 10}}>
          <Col span={4} style={{lineHeight: '32px', textAlign: 'right'}}>
            <span className="span-required">*</span>{messages('request.key634')/*用餐类型*/}：
          </Col>
          <Col span={18}>
            <Select
              showSearch
              placeholder={messages('common.please.select')}
              defaultActiveFirstOption={false}
              showArrow={true}
              value={(selectScene && selectScene.id) ? selectScene.id : undefined}
              onSelect={(e, opt) => this.selectScene(e, opt)}
              optionFilterProp="children"
              filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
              getPopupContainer={triggerNode => triggerNode.parentNode}>
              { currentScenes.map((scene) => {
                return (
                  <Option data-scene={scene} value={scene.id}>
                    {scene.name}
                  </Option>
                );
              })}
            </Select>
          </Col>
        </Row>
        {selectScene && (
          <Row style={{marginBottom: 10}}>
            <Col offset={4} span={18} className='show-value-font'>
              {messages('request.key635')/*有效时间：*/}
              {selectScene.durationType === 1 ? messages('request.key636')/*全天*/ : `${selectScene.startTime} - ${selectScene.endTime}`}
            </Col>
          </Row>
        )}
        <Divider />
        {diningConfig && diningConfig.city.show && (
          <Row>
            <Col span={4} style={{lineHeight: '32px', textAlign: 'right'}}>
              {diningConfig.city.required && <span className="span-required">*</span>}{messages('request.key629')/*用餐城市*/}：
            </Col>
            <Col span={8}>
              <TravelLocation
                value={cityName}
                intEnable={true}
                vendorType="standard"
                isEntity={false}
                onSelect={this.selectCity}
              />
            </Col>
          </Row>
        )}
        <Row style={{marginTop: 16}}>
          <Col span={4} style={{lineHeight: '32px', textAlign: 'right'}}>
            <span className="span-required">*</span>{messages('request.key637')/*用餐日期*/}：
          </Col>
          <Col span={8} className="date-item">
            <DatePicker
              placeholder={messages('common.please.select')}
              disabledDate={this.disabledDate}
              onChange={(value) => this.handleChangeDate(value, 'startDate')}
              value={startDate}
              allowClear
            />
          </Col>
          <Col span={2} style={{lineHeight: '32px', textAlign: 'center'}}>--</Col>
          <Col span={8} className="date-item">
            <DatePicker
              placeholder={messages('common.please.select')}
              disabledDate={this.disabledDate}
              onChange={(value) => this.handleChangeDate(value, 'endDate')}
              value={endDate}
              allowClear
            />
          </Col>
        </Row>
        {diningConfig && diningConfig.diningRule.show && !standardEnable && (
          <Row style={{marginTop: 16}}>
            <Col span={4} style={{lineHeight: '32px', textAlign: 'right'}}>
              <span className="span-required">*</span>{messages('request.key630')/*用餐标准*/}：
            </Col>
            <Col span={3}><Input value='CNY' disabled={true}/></Col>
            <Col span={4} offset={1}>
              <InputNumber
                placeholder={messages('common.please.input')}
                value={amount}
                onChange={num => this.handleChangeAmount(num, 'amount')}
                precision={2}
                style={{width: '100%'}}
                max={999999.99}
                min={0.01}
              />
            </Col>
          </Row>
        )}
        <Divider />
        <Row>
          <Col span={4} style={{lineHeight: '32px', textAlign: 'right'}}>
            {diningConfig.remark && diningConfig.remark.required && <span className="span-required">*</span>}{messages('common.remark')/*备注*/}：
          </Col>
          <Col span={18}>
            <TextArea
              maxLength="200"
              rows={4}
              placeholder={messages('common.please.input'/*请输入*/)}
              style={{resize: 'none'}}
              value={remark}
              onChange={this.handleChangeRemark}
            />
          </Col>
        </Row>
        <div className="slide-footer">
          <Button type="primary" onClick={this.handleSave} loading={loading}>{messages('common.ok')/*确定(*/}</Button>
          <Button onClick={this.closeDiningSlide}>{messages('common.cancel')/*返回(*/}</Button>
        </div>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    language: state.main.language
  };
}

const wrappedTravelDining = Form.create()(TravelDining);

export default connect(mapStateToProps)(wrappedTravelDining);
